<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { MagnifyingGlassIcon, AdjustmentsHorizontalIcon, XMarkIcon, CheckIcon } from '@heroicons/vue/24/outline'
import { Disclosure, DisclosureButton, DisclosurePanel } from '@headlessui/vue'
import { useServerStore } from '@/stores/server'

// 定义props
const props = defineProps<{
  isInternalOnly?: boolean
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'filter'): void
}>()

// 获取 Server 存储
const serverStore = useServerStore()

// 搜索查询
const searchQuery = ref(serverStore.searchQuery)

// 筛选选项
const categories = ref([
  { id: 'uncategorized', name: '未分类' },
  { id: 'utility', name: '工具类' },
  { id: 'search', name: '搜索' },
  { id: 'ai', name: 'AI模型' },
  { id: 'database', name: '数据库' },
  { id: 'web', name: 'Web服务' }
])

const providers = ref([
  { id: 'all', name: '全部' },
  { id: 'github', name: 'GitHub' },
  { id: 'internal', name: '内部服务' }
])

const languages = ref([
  { id: 'all', name: '全部' },
  { id: 'python', name: 'Python' },
  { id: 'javascript', name: 'JavaScript' },
  { id: 'typescript', name: 'TypeScript' },
  { id: 'go', name: 'Go' },
  { id: 'rust', name: 'Rust' },
  { id: 'java', name: 'Java' }
])

const sortOptions = ref([
  { id: 'name', name: '名称' },
  { id: 'updated_at', name: '更新时间' },
  { id: 'created_at', name: '创建时间' }
])

// 选中的过滤器
const selectedCategory = ref(serverStore.selectedCategory)
const selectedProvider = ref(serverStore.selectedProvider)
const selectedLanguage = ref(serverStore.selectedLanguage)
const selectedSortBy = ref(serverStore.sortBy)

// 是否显示筛选面板
const isFilterOpen = ref(false)

// 选中的分类名称
const selectedCategoryName = computed(() => {
  if (!selectedCategory.value) return '全部'
  const category = categories.value.find(c => c.id === selectedCategory.value)
  return category ? category.name : '全部'
})

// 选中的提供者名称
const selectedProviderName = computed(() => {
  if (!selectedProvider.value) return '全部'
  const provider = providers.value.find(p => p.id === selectedProvider.value)
  return provider ? provider.name : '全部'
})

// 选中的语言名称
const selectedLanguageName = computed(() => {
  if (!selectedLanguage.value) return '全部'
  const language = languages.value.find(l => l.id === selectedLanguage.value)
  return language ? language.name : '全部'
})

// 选中的排序方式名称
const selectedSortByName = computed(() => {
  if (!selectedSortBy.value) return '名称'
  const sort = sortOptions.value.find(s => s.id === selectedSortBy.value)
  return sort ? sort.name : '名称'
})

// 监听搜索输入
let searchTimeout: number | null = null
watch(searchQuery, (newValue) => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  searchTimeout = window.setTimeout(() => {
    serverStore.setSearchQuery(newValue)
    // 每次搜索查询变化时，强制重置数据并重新加载
    serverStore.resetData()
    emit('filter', newValue)
  }, 300)
})

// 选择分类
const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId === 'all' ? '' : categoryId
  serverStore.setCategory(selectedCategory.value)
  emit('filter')
}

// 选择提供者
const selectProvider = (providerId: string) => {
  selectedProvider.value = providerId === 'all' ? '' : providerId
  serverStore.selectedProvider = selectedProvider.value
  emit('filter')
}

// 选择语言
const selectLanguage = (languageId: string) => {
  selectedLanguage.value = languageId === 'all' ? '' : languageId
  serverStore.selectedLanguage = selectedLanguage.value
  emit('filter')
}

// 选择排序方式
const selectSortBy = (sortId: string) => {
  selectedSortBy.value = sortId
  serverStore.setSortBy(selectedSortBy.value)
  emit('filter')
}

// 重置所有过滤器
const resetFilters = () => {
  searchQuery.value = ''
  selectedCategory.value = ''
  selectedProvider.value = ''
  selectedLanguage.value = ''
  selectedSortBy.value = 'name'
  
  serverStore.resetFilters()
  serverStore.resetData() // 确保数据被重置
  emit('filter')
}

// 切换筛选面板显示
const toggleFilter = () => {
  isFilterOpen.value = !isFilterOpen.value
}
</script>

<template>
  <div class="bg-white dark:bg-gray-800 shadow rounded-lg mb-6">
    <div class="p-4">
      <!-- 搜索框 -->
      <div class="relative">
        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
          <MagnifyingGlassIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
        </div>
        <input
          v-model="searchQuery"
          type="text"
          class="form-input pl-10 pr-10 py-2 block w-full shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md"
          placeholder="搜索MCP Server ..."
        />
        <button 
          v-if="searchQuery"
          @click="searchQuery = ''; serverStore.setSearchQuery(''); serverStore.resetData(); emit('filter')"
          class="absolute inset-y-0 right-0 pr-3 flex items-center"
        >
          <XMarkIcon class="h-5 w-5 text-gray-400 hover:text-gray-500" aria-hidden="true" />
        </button>
      </div>
      
      <!-- 筛选器按钮 -->
      <!-- <div class="mt-3 flex items-center justify-between">
        <div class="flex items-center text-sm text-gray-500 dark:text-gray-400">
          <div v-if="isInternalOnly" class="mr-2">
            <span class="badge-primary">仅显示内部 Server </span>
          </div>
          <div class="flex space-x-2">
            <span v-if="serverStore.searchQuery" class="badge bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-300">
              搜索: {{ serverStore.searchQuery }}
            </span>
            <span v-if="selectedCategory" class="badge bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-300">
              分类: {{ selectedCategoryName }}
            </span>
            <span v-if="selectedProvider" class="badge bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300">
              提供者: {{ selectedProviderName }}
            </span>
            <span v-if="selectedLanguage" class="badge bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-300">
              语言: {{ selectedLanguageName }}
            </span>
            <span class="badge bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300">
              排序: {{ selectedSortByName }}
            </span>
          </div>
        </div>
        
        <div class="flex space-x-2">
          <button 
            @click="resetFilters"
            class="btn-outline py-1 px-2 text-xs"
            :disabled="!searchQuery && !selectedCategory && !selectedProvider && !selectedLanguage && selectedSortBy === 'name'"
          >
            重置
          </button>
          <button @click="toggleFilter" class="btn-outline py-1 px-2">
            <AdjustmentsHorizontalIcon class="h-4 w-4 mr-1" />
            筛选
          </button>
        </div>
      </div> -->
      
      <!-- 筛选面板 -->
      <div v-if="isFilterOpen" class="mt-4 bg-gray-50 dark:bg-gray-700 rounded-md p-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <!-- 分类筛选 -->
          <div>
            <h3 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">分类</h3>
            <div class="space-y-2">
              <div class="flex items-center">
                <button 
                  @click="selectCategory('all')" 
                  class="flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-primary-500 dark:hover:text-primary-400"
                >
                  <CheckIcon v-if="!selectedCategory" class="h-4 w-4 mr-1 text-primary-500 dark:text-primary-400" />
                  <span v-else class="w-4 mr-1"></span>
                  全部
                </button>
              </div>
              <div v-for="category in categories" :key="category.id" class="flex items-center">
                <button 
                  @click="selectCategory(category.id)" 
                  class="flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-primary-500 dark:hover:text-primary-400"
                >
                  <CheckIcon v-if="selectedCategory === category.id" class="h-4 w-4 mr-1 text-primary-500 dark:text-primary-400" />
                  <span v-else class="w-4 mr-1"></span>
                  {{ category.name }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 提供者筛选 -->
          <div>
            <h3 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">提供者</h3>
            <div class="space-y-2">
              <div v-for="provider in providers" :key="provider.id" class="flex items-center">
                <button 
                  @click="selectProvider(provider.id)" 
                  class="flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-primary-500 dark:hover:text-primary-400"
                >
                  <CheckIcon 
                    v-if="(provider.id === 'all' && !selectedProvider) || selectedProvider === provider.id" 
                    class="h-4 w-4 mr-1 text-primary-500 dark:text-primary-400" 
                  />
                  <span v-else class="w-4 mr-1"></span>
                  {{ provider.name }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 语言筛选 -->
          <div>
            <h3 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">开发语言</h3>
            <div class="space-y-2">
              <div v-for="language in languages" :key="language.id" class="flex items-center">
                <button 
                  @click="selectLanguage(language.id)" 
                  class="flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-primary-500 dark:hover:text-primary-400"
                >
                  <CheckIcon 
                    v-if="(language.id === 'all' && !selectedLanguage) || selectedLanguage === language.id" 
                    class="h-4 w-4 mr-1 text-primary-500 dark:text-primary-400" 
                  />
                  <span v-else class="w-4 mr-1"></span>
                  {{ language.name }}
                </button>
              </div>
            </div>
          </div>
          
          <!-- 排序方式 -->
          <div>
            <h3 class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">排序方式</h3>
            <div class="space-y-2">
              <div v-for="sortOption in sortOptions" :key="sortOption.id" class="flex items-center">
                <button 
                  @click="selectSortBy(sortOption.id)" 
                  class="flex items-center text-sm text-gray-700 dark:text-gray-300 hover:text-primary-500 dark:hover:text-primary-400"
                >
                  <CheckIcon v-if="selectedSortBy === sortOption.id" class="h-4 w-4 mr-1 text-primary-500 dark:text-primary-400" />
                  <span v-else class="w-4 mr-1"></span>
                  {{ sortOption.name }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template> 